package day08.handler;

import day08.packet.*;
import day08.util.PacketCodeC;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;

/**
 * @author chenshijie
 * @date 2023/12/23 15:34
 */
//@ChannelHandler.Sharable
public class ServerHandler extends ChannelInboundHandlerAdapter {

    private final static String USERNAME = "yu";
    private final static String PASSWORD = "password";

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        Packet packet = PacketCodeC.INSTANCE.decode((ByteBuf) msg);

        if (packet instanceof LoginRequestPacket) {

            loginResponse(ctx, (LoginRequestPacket) packet);

        } else if (packet instanceof MessageRequestPacket) {

            messageResponse(ctx, (MessageRequestPacket) packet);
        } else {
            System.out.println("查无此数据类型");
        }



    }

    private static boolean valid(LoginRequestPacket loginRequestPacket) {
        return USERNAME.equals(loginRequestPacket.getUsername()) && PASSWORD.equals(loginRequestPacket.getPassword());
    }

    private static void loginResponse(ChannelHandlerContext ctx, LoginRequestPacket packet) {
        LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
        loginResponsePacket.setVersion(packet.getVersion());
//        LoginRequestPacket loginRequestPacket = (LoginRequestPacket) packet;

        // 登录校验
        if (valid(packet)) {
            // 成功
            System.out.println("校验成功");
            loginResponsePacket.setStatus(200);
            loginResponsePacket.setMsg("登录成功");

        } else {
            // 错误
            System.out.println("校验失败");
            loginResponsePacket.setStatus(405);
            loginResponsePacket.setMsg("密码错误或者账号不存在");
        }

        // 编码
        ByteBuf byteBuf = PacketCodeC.INSTANCE.encode(ctx.alloc(), loginResponsePacket);
        ctx.channel().writeAndFlush(byteBuf);
    }

    private static void messageResponse(ChannelHandlerContext ctx, MessageRequestPacket messageRequestPacket) {
        MessageResponsePacket messageResponsePacket = new MessageResponsePacket();
        messageResponsePacket.setVersion(messageRequestPacket.getVersion());

        System.out.println(new Date() + ": 收到客户端消息: " + messageRequestPacket.getMessage());

        messageResponsePacket.setMessage("服务段回复:【" + messageRequestPacket.getMessage() + "】");

        ByteBuf byteBuf = PacketCodeC.INSTANCE.encode(ctx.alloc(), messageResponsePacket);
        ctx.channel().writeAndFlush(byteBuf);
    }
}
